package com.east.config.shiro;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.east.bean.Privilege;
import com.east.bean.Role;
import com.east.bean.User;
import com.east.dao.PrivilegeMapper;
import com.east.dao.UserMapper;
import com.east.service.system.LoginService;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.util.*;

public class MyShiroRealm extends AuthorizingRealm {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

    //如果项目中用到了事物，@Autowired注解会使事物失效，可以自己用get方法获取值
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PrivilegeMapper privilegeMapper;
    /**
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     *
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        logger.info("---------------- 执行 Shiro 凭证认证 ----------------------");
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String name = token.getUsername();
        String password = String.valueOf(token.getPassword());
        User user = new User();
        user.setuAccount(name);
        user.setuPassword(password);
        // 从数据库获取对应用户名密码的用户
        User userList = loginService.getUser(user);
        List<Privilege> findByPrivilege = loginService.findByPrivilege(userList);
        userList.setPrivileges(findByPrivilege);
        String jsonString = JSON.toJSON(userList).toString();
        String string=null;
		try {
			byte[] encode = Base64.encodeBase64(jsonString.getBytes("UTF-8"));
			string = new String(encode,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        if (userList != null) {
            // 用户为禁用状态
            if (userList.getuState() != 1) {
                throw new DisabledAccountException();
            }
            logger.info("---------------- Shiro 凭证认证成功 ----------------------");
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
            		string, //用户
                    userList.getuPassword(), //密码
                    getName()  //realm name
            );
            return authenticationInfo;
        }
        throw new UnknownAccountException();
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("---------------- 执行 Shiro 权限获取 ---------------------");
        Object principal = principals.getPrimaryPrincipal();
        String user=(String)principal;
        byte[] decodeBase64 = Base64.decodeBase64(user);
        String string=null;
		try {
			string = new String(decodeBase64,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		User stu = JSON.parseObject(string,new TypeReference<User>() {});
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            //List<Role> list = loginService.findByRolePrivile(stu.getuId());
          //角色名的集合
    		//Set<String> roles = new HashSet<String>();
    		//权限名的集合
    		Set<String> permissions = new HashSet<String>();
    		/*Iterator<Role> it = list.iterator();
    		while(it.hasNext()){
    			roles.add(it.next().getName());
    			for(Privilege per:it.next().getPrivileges()){
    				permissions.add(per.getpUrl());
    			}
    		}*/
    		List<Privilege> findByPrivQX = privilegeMapper.findByPrivQX();
    		for (Privilege privilege : findByPrivQX) {
    			permissions.add(privilege.getpUrl());
			}
            //authorizationInfo.addRole("admins");
            //Set<String> permissions = userService.findPermissionsByUserId(userLogin.getId());
            authorizationInfo.addStringPermissions(permissions);
        logger.info("---- 获取到以下权限 ----");
        logger.info(authorizationInfo.getStringPermissions().toString());
        logger.info("---------------- Shiro 权限获取成功 ----------------------");
        return authorizationInfo;
    }

}